﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using DomainModel.Entities;
using DomainModel.Abstract;

namespace DomainModel.Concrete
{
    public class SqlApplicationsRepository : IApplicationsRepository
    {
        private Table<Application> applicationsTable;

        public SqlApplicationsRepository(string connectionString)
        {
            applicationsTable = (new DataContext(connectionString)).GetTable<Application>();
        }

        public IQueryable<Application> Applications
        {
            get { return applicationsTable; }
        }

        public void SaveApplication(Application application)
        {
            if (application.ApplicationID == 0)
            {
                //It's a new application
                applicationsTable.InsertOnSubmit(application);
            }
            else
            {
                //It's an existing application
                applicationsTable.Attach(application);

                //Tell DataContext to detect any changes since last save? Not entirely sure about this...
                applicationsTable.Context.Refresh(RefreshMode.KeepCurrentValues, application);
            }

            //Submit the changes
            applicationsTable.Context.SubmitChanges();
        }

        public void DeleteApplication(Application application)
        {
            applicationsTable.DeleteOnSubmit(application);
            applicationsTable.Context.SubmitChanges();
        }
    }
}
